<template>
  <a-modal
    title="添加时间间隔"
    :width="480"
    :visible="visible"
    :maskClosable="false"
    :keyboard="false"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <a-form :form="form">
      <a-form-item label="时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
        <a-form-item style="display: inline-block; margin-right: 12px;">
          <a-input-number v-decorator="['time']" :min="1" :max="maxTime" :precision="0" @blur="onBlurTime" />
        </a-form-item>
        <a-form-item :style="{ display: 'inline-block', width: 'calc(50% - 12px)' }">
          <a-select v-model="unit" style="width: 100%">
            <a-select-option value="day">天</a-select-option>
            <a-select-option value="hour">小时</a-select-option>
            <a-select-option value="min">分</a-select-option>
          </a-select>
        </a-form-item>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script>
export default {
  name: 'TimeForm',
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 13 }
      },
      tempId: 0,
      visible: false,
      form: this.$form.createForm(this),
      unit: 'min'
    }
  },
  computed:{
    maxTime(){
      switch(this.unit){
        case 'min':
          return 60*24*360
        case 'hour':
          return 24*360
        case 'day':
          return 360
      }
    }
  },
  methods: {
    show(values) {
      this.visible = true
      this.tempId = values.tempId
      this.$nextTick(() => {
        if(!!values.intervalTime){
          const temp = this.fitUnit(values.intervalTime)
          this.form.setFieldsValue({
            time: temp.val
          })
          this.unit = temp.unit
        } else {
          this.resetForm()
        }
      })
    },

    fitUnit(min){
      if(min % 1440 === 0){
        return {
          val: min / 1440,
          unit: 'day'
        }
      } else if(min % 60 === 0){
        return {
          val: min / 60,
          unit: 'hour'
        }
      } else {
        return {
          val: min,
          unit: 'min'
        }
      }
    },

    onBlurTime(e) {
      if (!e.target.value) {
        this.form.setFieldsValue({ time: 1 })
      }
    },

    handleSubmit() {
      const {
        form: { validateFields, getFieldsValue }
      } = this
      validateFields((errors, values) => {
        if (!errors) {
          const { time } = getFieldsValue()
          const intervalTime = time * (this.unit === 'day' ? 1440 : this.unit === 'hour' ? 60 : 1)
          this.$emit('ok', { tempId: this.tempId, intervalTime })
          this.handleCancel()
        }
      })
    },

    handleCancel() {
      this.resetForm()
      this.visible = false
    },

    resetForm() {
      this.form.setFieldsValue({ time: 1 })
    }
  }
}
</script>

<style></style>
